
package com.eightbears.beboy.ui.user.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.SearchAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.SearchUser;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.greendao.Friends;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.widget.EaseAlertDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_PAGE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAM_URL_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_SEARCH;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;

public class AddContactActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener{

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;


    private EditText editText;
    private RelativeLayout searchedUserLayout;
    private String toAddUsername;
    private ProgressDialog progressDialog;

    private String searchKey;
    private int page = 1;
    private int requestType = 0;
    private boolean isErr = true;
    private int isEnd = 0;

    private SearchAdapter mSearchAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.eightbears.beboy.R.layout.em_activity_add_contact);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initView();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        TextView mTextView = (TextView) findViewById(R.id.add_list_friends);
        editText = (EditText) findViewById(com.eightbears.beboy.R.id.edit_note);
        String strAdd = getResources().getString(com.eightbears.beboy.R.string.add_friend);
        mTextView.setText(strAdd);
        String strUserName = getResources().getString(com.eightbears.beboy.R.string.user_name);
        editText.setHint(strUserName);
        searchedUserLayout = (RelativeLayout) findViewById(com.eightbears.beboy.R.id.ll_user);
        initAdapter();

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent(){
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchKey = s.toString();
                findFriend();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
        });
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

    }

    /**
     * search contact
     *
     * @param v
     */
    public void searchContact(View v) {
        swipeLayout.setRefreshing(true);
        searchKey = editText.getText().toString();
        findFriend();
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(AddContactActivity.this));
        mSearchAdapter = new SearchAdapter();
        mSearchAdapter.openLoadAnimation();
        mSearchAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(mSearchAdapter);
        mSearchAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SearchUser.DataBean user = (SearchUser.DataBean) adapter.getData().get(position);
                toAddUsername = user.getUser_id();
                if(view.getId() == R.id.add_friend) {
                    addContact();
                } else {
                    startLocalActivity(AddContactActivity.this, UserInfoActivity.class, PARAMS_USER_INFO, user.getUser_id());
                }

            }
        });
    }

    /**
     * 查找好友
     */
    private void findFriend() {
        //获取token
        OkHttpUtils.get().url(URL_RESET_SEARCH)
                .addHeader(KEY_HTTP_HEADER, "Bearer " +  SPUtil.getAccessToken())
                .addParams("type", "1").addParams("keyword", searchKey)
                .addParams(PARAM_URL_PAGE, String.valueOf(page))
                .addParams(PARAM_URL_SIZE, PARAMS_PAGE_SIZE)
                .addParams("no_need_friends", "1")
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                SearchUser searchUser = GsonUtil.fromJson(response, SearchUser.class);
                if(searchUser.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)){
                    isEnd = Integer.parseInt(searchUser.getData().getIs_end());
                    if (page == 1)
                        mSearchAdapter.setNewData(searchUser.getData().getList());
                    else {
                        mSearchAdapter.addData(searchUser.getData().getList());
                        mSearchAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(AddContactActivity.this, status_error);
            }
        });
    }


    /**
     * add contact
     */
    public void addContact() {

        Friends friends = FriendsCache.getInstance(this).getCacheByName(toAddUsername);
        if (null == friends) {
            friends = new Friends();
            friends.setUser_id("");
        }

        if (toAddUsername.equals(SPUtil.getUser().getData().getUser_id())) {
            new EaseAlertDialog(this, com.eightbears.beboy.R.string.not_add_myself).show();
            return;
        }

        if (toAddUsername.equals(friends.getUser_id())) {
            if (EMClient.getInstance().contactManager().getBlackListUsernames().contains(toAddUsername)) {
                new EaseAlertDialog(this, R.string.user_already_in_contactlist).show();
                return;
            }
            new EaseAlertDialog(this, com.eightbears.beboy.R.string.This_user_is_already_your_friend).show();
            return;
        }
        progressDialog = new ProgressDialog(this);
        String message = getResources().getString(com.eightbears.beboy.R.string.Is_sending_a_request);
        progressDialog.setMessage(message);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {

                try {
                    //demo use a hardcode reason here, you need let user to input if you like
                    String s = getResources().getString(com.eightbears.beboy.R.string.Add_a_friend);
                    EMClient.getInstance().contactManager().addContact(toAddUsername, s);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s1 = getResources().getString(com.eightbears.beboy.R.string.send_successful);
                            Toast.makeText(getApplicationContext(), s1, Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s2 = getResources().getString(com.eightbears.beboy.R.string.Request_add_buddy_failure);
                            Toast.makeText(getApplicationContext(), s2 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    public void back(View v) {
        finish();
    }

    @Override
    public void onRefresh() {
        mSearchAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                mSearchAdapter.getData().clear();
                findFriend();
                mSearchAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    mSearchAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        findFriend();
                    } else {
                        isErr = true;
                        Toast.makeText(AddContactActivity.this, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        mSearchAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Override
    public void finish() {
        super.finish();
        InputMethodUtils.hindInputMethod(this);
    }
}
